<template>
  <div id="body">
    <!-- 短信登陆 -->
    <el-card
      v-show="mode == 0"
      class="box-card formCard"
      v-loading="loading"
      :element-loading-text="loadingText">
      <div slot="header" class="clearfix">
        <span>短信登录</span>
      </div>
      <el-form
        ref="loginMsgForm"
        :rules="rules"
        :model="loginMsgForm"
        label-width="80px">
        <el-form-item label="账号" prop="phone">
          <el-input
            type="text"
            placeholder="请输入手机号码"
            v-model="loginMsgForm.phone"
          ></el-input>
        </el-form-item>
        <el-row type="flex">
          <el-col :span="16">
            <el-form-item label="验证码" prop="msg">
              <el-input
                placeholder="请输入验证码"
                v-model="loginMsgForm.msg"
                maxlength="6"
                show-word-limit
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="2">
            <el-button
              id="msgBtn"
              @click="getMsgCode()"
              :disabled="msgBtnDisable"
              >{{ msgBtnText }}</el-button>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button type="primary" @click="loginMsg()">短信登录</el-button>
          <el-button
            @click="
              resetForm('loginMsgForm');
              changeMode(1);
            "
            >账号登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 账号登录 -->
    <el-card v-show="mode == 1" class="box-card formCard">
      <div slot="header" class="clearfix">
        <span>账号登录</span>
      </div>
      <el-form
        ref="loginAccountForm"
        :rules="rules"
        :model="loginAccountForm"
        label-width="80px">
        <el-form-item label="账号" prop="phone">
          <el-input
            type="text"
            placeholder="请输入手机号码"
            v-model="loginAccountForm.phone"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="pwd">
          <el-input
            type="password"
            placeholder="请输入密码"
            v-model="loginAccountForm.pwd"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loginAccount()">账号登录</el-button>
          <el-button
            @click="
              resetForm('loginAccountForm');
              changeMode(0);
            "
            >短信登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { isStrEmpty } from "@/utils/util.js";
export default {
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.loginMsgForm.confirmPwd !== "") {
          this.$refs.loginMsgForm.validateField("confirmPwd");
        }
        callback();
      }
    };
    return {
      loading: false,
      loadingText: "",
      mode: 1,
      msgBtnText: "获取验证码",
      msgBtnDisable: false,
      loginMsgForm: {
        phone: "",
        name: "",
        msg: "",
        pwd: "",
        confirmPwd: "",
      },
      loginAccountForm: {
        phone: "",
        pwd: "",
      },
      rules: {
        name: [{ required: true, message: "请输入用户名", trigger: "blur" }],
        pwd: [{ required: true, validator: validatePass, trigger: "blur" }],
        phone: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          {
            min: 11,
            max: 11,
            pattern: new RegExp(/^\d{11}$/, "g"),
            message: "请输入11位手机号码",
            trigger: "blur",
          },
        ],
        msg: [
          { required: true, message: "请输入验证码", trigger: "blur" },
          {
            min: 6,
            max: 6,
            pattern: new RegExp(/^\d{6}$/, "g"),
            message: "请输入6位数字",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          alert("submit!");
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    /**
     * 切换注册或登录
     */
    changeMode(num) {
      this.mode = num;
    },
    /**
     * 短信登录
     */
    loginMsg() {
      this.$refs["loginMsgForm"].validate((valid) => {
        if (valid) {
          this.loading = true;
          this.loadingText = "正在登录，请稍后";
          //axios请求方式，通过this.request使用分装好的axios实例
          this.request
            .post("/access/msgCodeLogin", {
              phone: this.loginMsgForm.phone,
              msg: this.loginMsgForm.msg,
            })
            .then((res) => {
              this.loading = false;
              if ((res.code = 200)) {
                this.$message({
                  message: res.msg,
                  type: "success",
                });
                //把用户数据保存到本地
                localStorage.setItem("loginUser", JSON.stringify(res.data));
                //跳转到主页
                this.$router.replace("/main");
              } else {
                this.$message({
                  message: res.msg,
                  type: "error",
                });
              }
            })
            .catch((err) => {
              this.loading = false;
            });
        } else {
          this.$message({
            message: "请先规范填写表单信息",
            type: "warning",
          });
        }
      });
    },
    /**
     * 账号登录
     */
    loginAccount() {
      this.$refs["loginAccountForm"].validate((valid) => {
        if (valid) {
          this.loading = true;
          this.loadingText = "正在登录，请稍后";
          //axios请求方式，通过this.request使用分装好的axios实例
          this.request
            .post("/access/loginUser", {
              phone: this.loginAccountForm.phone,
              pwd: this.loginAccountForm.pwd,
            })
            .then((res) => {
              this.loading = false;
              if ((res.code == 200)) {
                this.$message({
                  message: res.msg,
                  type: "success",
                });
                //把用户数据保存到本地
                localStorage.setItem("loginUser", JSON.stringify(res.data));
                //跳转到主页
                this.$router.replace("/main");
              } else {
                this.$message({
                  message: res.msg,
                  type: "error",
                });
              }
            })
            .catch((err) => {
              this.loading = false;
            });
        } else {
          this.$message({
            message: "请先规范填写表单信息",
            type: "warning",
          });
        }
      });
    },
    /**
     * 获取验证码
     */
    getMsgCode() {
      var that = this;
      this.$refs["loginMsgForm"].validateField("phone", (err) => {
        if (isStrEmpty(err)) {
          this.msgBtnDisable = true;
          this.request
            .get("/access/getMsgCode", {
              params: {
                phone: this.loginMsgForm.phone
              },
            })
            .then((res) => {
              if ((res.code == 200)) {
                this.$message({
                  message: res.msg,
                  type: "success",
                });
                var orignText = this.msgBtnText;
                var i = 60;
                const interval = setInterval(function () {
                  that.msgBtnText = i + "秒后获取";
                  if (i-- <= 0) {
                    interval && clearInterval(interval);
                    that.msgBtnDisable = false;
                    that.msgBtnText = orignText;
                  }
                }, 1000);
              } else {
                this.$message({
                  message: res.msg,
                  type: "error",
                });
                that.msgBtnDisable = false;
              }
            })
            .catch((err) => {
              that.msgBtnDisable = false;
            });
        }
      });
    },
  },
};
</script>

<style scoped>
#body {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: url(../assets/background.jpg) 0% 0% / cover no-repeat;
}
.formCard {
  margin: 100px;
}
.text {
  font-size: 14px;
}
.item {
  margin-bottom: 18px;
}
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}
.box-card {
  width: 480px;
}
</style>